package net.codesree.action;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.codesree.action.IAction;
import net.codesree.utils.TokenUtil;

public abstract class AbstractAction implements IAction {

 public static final String TRANSACTION_TOKEN_KEY="TRANSACTION_KEY";
 public static final String TOKEN_KEY="TOKEN_KEY";

 protected String fromUrl=null;
 protected String nextUrl=null;
 protected String errorUrl=null;
 protected HttpSession sess=null;
 protected HttpServletRequest req=null;
 protected HttpServletResponse res=null;  
 protected ServletContext application=null;
 
 public AbstractAction() {}
 
 public abstract void preProcess() throws IOException,ServletException;
 public abstract void processRequest() throws IOException,ServletException;
 public abstract void postProcess() throws IOException,ServletException;

 public void execute(ServletContext _app,HttpServletRequest _req,HttpServletResponse _res) 
  throws IOException,ServletException {
  this.application=_app;
  this.req=_req;
  this.res=_res;
  preProcess();
  processRequest();
  postProcess();
 }

 public final void redirect() throws IOException,ServletException {
  this.res.sendRedirect(nextUrl);
 }

 public final void forward() throws IOException,ServletException {
  this.req.getRequestDispatcher(nextUrl).forward(this.req,this.res);
 }

 public boolean isTokenValid(boolean reset) {
  // Retrieve the current session for this request
  HttpSession session = this.req.getSession(false);
  if (session == null) {
   return false;
  }  
  // Retrieve the transaction token from this session, and
  // reset it if requested
  String saved = (String) session.getAttribute(TRANSACTION_TOKEN_KEY);
  if (saved == null) {
   return false;
  }  
  if (reset) { this.resetToken(); }  
  // Retrieve the transaction token included in this request
  String token = this.req.getParameter(TOKEN_KEY);
  if (token == null) {
   return false;
  }
  return saved.equals(token);
 }

 public void resetToken() {
  HttpSession session = this.req.getSession(false);
  if (session == null) {
    return;
  }
  session.removeAttribute(TRANSACTION_TOKEN_KEY);
 }
 
 public void saveToken() {
  HttpSession session = this.req.getSession();
  String token = new TokenUtil().generateToken();
  if (token != null) {
   session.setAttribute(TRANSACTION_TOKEN_KEY, token);
  }
 }
 
}
